import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import Welcome from '../components/welcome.vue'
import User from '../components/users.vue'
import Rights from '../components/right.vue'
import Roles from '../components/roles.vue'
import Categories from '../components/goods/categories.vue'
import Params from '../components/goods/params.vue'
import Goods from '../components/goods/goods.vue'
import Addgoods from '../components/goods/add.vue'
import Order from '../components/order.vue'
import Reports from '../components/reports.vue'
Vue.use(VueRouter)

const routes = [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
        path: '/home',
        component: Home,
        redirect: '/welcome',
        children: [
                { path: '/welcome', component: Welcome },
                { path: '/users', component: User },
                { path: '/rights', component: Rights },
                { path: '/roles', component: Roles },
                { path: '/categories', component: Categories },
                { path: '/params', component: Params },
                { path: '/goods', component: Goods },
                { path: '/goods/add', component: Addgoods },
                { path: '/orders', component: Order },
                { path: '/reports', component: Reports }
            ] // url 是users时，调用user组件展示在router-view里面
    }
]

const router = new VueRouter({
    routes
})

// 路由导航守卫
// to表示在跳转前，from表示从哪个路径跳转，next表示放行
router.beforeEach((to, from, next) => {
    // 如果用户访问的是登录页，直接放行
    if (to.path === '/login') return next()
        // 从session获取里面的token值
    const tokenStr = window.sessionStorage.getItem('token')
        // 如果没有token，说明用户没有登录,那么跳转到login页面
    if (!tokenStr) return next('/login')
    next()
})

export default router